//
//  JYHouseLoanViewController.swift
//  JYCalculate
//
//  Created by 何治军 on 2018/10/30.
//  Copyright © 2018 何治军. All rights reserved.
//

import UIKit

class JYHouseLoanViewController: JYBaseViewController,UITableViewDataSource,UITableViewDelegate {

    
    var caculateDataArray:[JYHouseLoanModel] = []
    
    
    /// 还款方式
    private var typeArray:[JYHouseLoanModel] {
        var array:[JYHouseLoanModel]=[]
        for index in 0..<2 {
            let model = JYHouseLoanModel()
            model.title = "还款方式"
            if index == 0 {
                model.descri = "等额本息(每月等额还款)"
            }else{
                model.descri = "等额本金(每月递减还款)"
            }
            model.identification = "\(index)"
            array.append(model)
        }
        return array
    }
    
    /// 按揭年数
    private var yearArray:[JYHouseLoanModel] {
        var array:[JYHouseLoanModel]=[]
        for index in 1...30 {
            let model = JYHouseLoanModel()
            model.title = "按揭年数"
            model.descri = "\(index)年"
            if index <= 5 {
                model.rate1 = "4.75"
                model.rate2 = "2.75"
            }else{
                model.rate1 = "4.9"
                model.rate2 = "3.25"
            }
            model.identification = "\(index)"
            array.append(model)
        }
        return array
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Localized("function-house-loan")
        NotificationCenter.default.addObserver(self, selector: #selector(changeForKeyBoard(_:)), name: NSNotification.Name(rawValue: "UIKeyboardWillShowNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector:  #selector(changeForKeyBoard(_:)), name: NSNotification.Name(rawValue: "UIKeyboardWillHideNotification"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    override func setUpUI() {
        tableView.tableHeaderView = topView
        tableView.tableFooterView = bottomView
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(JYHouseLoanCell.self, forCellReuseIdentifier: "JYHouseLoanCell")
        self.view.addSubview(tableView)
        self.view.addSubview(caculateView)
        self.view.addSubview(picker)
    }
    
    override func setDefaultInfo() {
        
        let model = JYHouseLoanModel()
        model.title = "房贷总额"
        model.defaultDescri = "请输入金额"
        self.caculateDataArray.append(model)
        self.caculateDataArray.append(self.typeArray[0])
        self.caculateDataArray.append(self.yearArray[0])
        let model1 = JYHouseLoanModel()
        model1.title = "首次还款日"
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "yyyy-MM-dd"
        model1.descri = dateFormat.string(from: Date())
        self.caculateDataArray.append(model1)
        
        self.tableView.reloadData()
        self.bottomView.defeaultRate = self.topView.segment.selectedSegmentIndex == 0 ? self.caculateDataArray[2].rate1 : self.caculateDataArray[2].rate2 ;

    }
    override func setTheLayout() {
        tableView.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.caculateView.mas_top)
        }
        caculateView.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(88)

        }
        picker.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.view.mas_bottom)
            make?.height.mas_equalTo()(216)
        }
    }
    
    //MARK: - UITableViewDataSource,UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.caculateDataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = JYHouseLoanCell.init(style: .default, reuseIdentifier: "JYHouseLoanCell")
        cell.model = self.caculateDataArray[indexPath.row]
        if indexPath.row == 0 {
            cell.accessoryType = .none
            cell.cellMode = .one
        }else{
            cell.accessoryType = .disclosureIndicator
            cell.cellMode = .normal
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        hiddenKeyBoard()
        if indexPath.row == 1 {
            let vc = JYHouseLoanListViewController()
            vc.dataArray = self.typeArray
            vc.currentSelectedModel = self.caculateDataArray[1]
            vc.selectedModelBlock = { [weak self] model in
                let strongSelf = self
                strongSelf?.caculateDataArray[1] = model
                strongSelf?.changeTheLoanType()
                strongSelf?.tableView.reloadData()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }else if indexPath.row == 2 {
            let vc = JYHouseLoanListViewController()
            vc.dataArray = self.yearArray
            vc.currentSelectedModel = self.caculateDataArray[2]
            vc.selectedModelBlock = { [weak self] model in
                let strongSelf = self
                strongSelf?.caculateDataArray[2] = model
                strongSelf?.changeTheLoanType()
                strongSelf?.tableView.reloadData()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }else if indexPath.row == 3 {
            if self.picker.isHidden {
                hiddenThePicker(hidden: false)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        hiddenKeyBoard()
    }
    
    //picker的隐藏和显示
    func hiddenThePicker(hidden:Bool) {
        if hidden {
            UIView.animate(withDuration: 0.25, animations: {
                self.picker.transform = CGAffineTransform(translationX: 0, y: 0)
            }) { (final) in
                self.picker.isHidden = true
            }
        }else
        {
            self.picker.isHidden = false;
            UIView.animate(withDuration: 0.25) {
                self.picker.transform = CGAffineTransform(translationX: 0, y: -216)
            }
        }
    }
    //键盘改变事接收的通知事件
    @objc func changeForKeyBoard(_ noti:NSNotification){
        let duration = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        if noti.name.rawValue == "UIKeyboardWillShowNotification" {
            let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as! CGRect
            UIView.animate(withDuration: duration) {
                self.view.transform = CGAffineTransform(translationX: 0, y: -rect.height)
                self.tableView.contentInset = UIEdgeInsets(top: rect.height, left: 0, bottom: 0, right: 0)
                self.tableView.bounces = true
            }
        }else{
            UIView.animate(withDuration: duration) {
                self.view.transform = CGAffineTransform(translationX: 0, y: 0)
                self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                self.tableView.bounces = false
            }
        }
    }
    //MARK: - 修改贷款方式
    @objc func changeTheLoanType(){
        hiddenKeyBoard()
        self.bottomView.defeaultRate = self.topView.segment.selectedSegmentIndex == 0 ? self.caculateDataArray[2].rate1 : self.caculateDataArray[2].rate2 ;
    }
    
    //MARK: - 开始计算结果
    @objc func caculate() {
        hiddenKeyBoard()
        if self.caculateDataArray[0].descri == "" {
            let vc = UIAlertController(title: "请输入贷款额度", message: nil, preferredStyle: .alert)
            let cancel = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            vc.addAction(cancel)
            self.present(vc, animated: true, completion: nil)
            return
        }
        
        let vc = JYHouseLoanResultViewController()
        vc.caculateDic = (["loanType":"\(self.topView.segment.selectedSegmentIndex)","money":self.caculateDataArray[0].descri,"repaymentType":"\(self.caculateDataArray[1].identification)","year":self.caculateDataArray[2].identification,"rate":self.bottomView.resultLab.text] as! Dictionary<String, String>)
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK: - 点击时间选择器
    @objc func clickThePicker(_ pick:UIDatePicker){
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        self.caculateDataArray[3].descri = dateFormatter.string(from: pick.date)
        self.tableView.reloadData()
    }
    
    // MARK: -隐藏键盘
    @objc private func hiddenKeyBoard() {
        UIApplication.shared.keyWindow?.endEditing(true)
        if self.picker.isHidden == false {
            hiddenThePicker(hidden: true)
        }
    }
    
    //MARK: - 组件
    private lazy var topView:JYHouseLoanTopView = {
        let v = JYHouseLoanTopView.init(frame: CGRect(x: 0, y: 0, width: 10, height: 60))
        v.titleArray = ["商业贷款","公积金贷款"]
        v.segment.selectedSegmentIndex = 0
        v.topLine.isHidden = false
        v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hiddenKeyBoard)))
        v.segment.addTarget(self, action: #selector(changeTheLoanType), for: .valueChanged)
        return v
    }()
    
    private lazy var tableView:UITableView = {
        let tab = UITableView()
        tab.separatorStyle = .none
        tab.backgroundColor = JYVCBackGroundColor
        return tab
    }()
    
    private lazy var bottomView:JYHouseLoanBottomView = {
        let v = JYHouseLoanBottomView.init(frame: CGRect(x: 0, y: 0, width: 100, height: 120))
        v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hiddenKeyBoard)))
        return v
    }()
    
    private lazy var caculateView:JYHouseLoanCaculateBtnView = {
        let v = JYHouseLoanCaculateBtnView()
        v.caculateBtn.addTarget(self, action: #selector(caculate), for: .touchUpInside)
        return v
    }()
    
    private lazy var picker:UIDatePicker = {
        let p = UIDatePicker()
        p.backgroundColor = JYDetailGrayColor
        p.datePickerMode = .date
        p.isHidden = true
        p.addTarget(self, action: #selector(clickThePicker(_:)), for: .valueChanged)
        return p
    }()
}

//MARK: -  头部选择器
class JYHouseLoanTopView: JYBaseView {
    
    var titleArray:[String] = []{
        didSet{
            for index in 0..<titleArray.count {
                self.segment.insertSegment(withTitle: titleArray[index], at: index, animated: false)
            }
        }
    }
    
    override func setUpUI() {
        super.setUpUI()
        self.addSubview(segment)
    }
    override func setTheConstraints() {
        super.setTheConstraints()
        segment.mas_updateConstraints { (make) in
            make?.center.mas_equalTo()(self)
            make?.left.mas_lessThanOrEqualTo()(self)?.offset()(16)
        }
    }
    
    lazy var segment:UISegmentedControl = {
        let s = UISegmentedControl()
        s.tintColor = JYNavigationBarColor
        return s
    }()
}

//MARK: -  底部组件
class JYHouseLoanBottomView: JYBaseView,UITextFieldDelegate {
    
    var defeaultRate:String = "" {
        didSet{
            self.firstText.placeholder = defeaultRate
            self.firstText.text = defeaultRate
            self.tipLab.text = "当前基准利率:\(defeaultRate)%"
            caculateTheResultRate()
        }
    }
    
    ///计算利率
    @objc func caculateTheResultRate() {
        let first = self.firstText.text == "" ? self.firstText.placeholder : self.firstText.text
        let second = self.secondText.text == "" ? self.secondText.placeholder : self.secondText.text
        self.resultLab.text = "\(MultiplicationM(first!, b: second!).stringValue)%"
    }
    
    //MARK: - UITextFieldDelegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string=="" {
            return true
        }
        if (textField.text! as NSString).length + (string as NSString).length > 11 {
            return false
        }
        if textField.text == "" && string == "." {
            return false
        }
        if (textField.text?.contains("."))! {
            if (textField.text!.components(separatedBy: ".").last! as NSString).length >= 2 || string.contains(".") {
                return false
            }
        }else{
            if (textField.text! as NSString).length >= 3 && string != "." {
                return false
            }
        }
        return true
    }
    
    override func setUpUI() {
        super.setUpUI()
        self.addSubview(titleLab)
        self.addSubview(firstText)
        self.addSubview(typeLab)
        self.addSubview(secondText)
        self.addSubview(equalLab)
        self.addSubview(resultLab)
        self.addSubview(tipLab)
    }
    override func setTheConstraints() {
        super.setTheConstraints()
        titleLab.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self)?.offset()(16)
            make?.centerY.mas_equalTo()(self.mas_top)?.offset()(30)
        }
        firstText.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.titleLab.mas_right)?.offset()(16)
            make?.centerY.mas_equalTo()(self.titleLab)
            make?.height.mas_equalTo()(30)
        }
        typeLab.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.firstText.mas_right)
            make?.centerY.mas_equalTo()(self.titleLab)
            make?.width.mas_equalTo()(30)
        }
        secondText.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.typeLab.mas_right)
            make?.centerY.mas_equalTo()(self.titleLab)
            make?.right.mas_greaterThanOrEqualTo()(self)?.offset()(-16)
            make?.width.mas_equalTo()(self.firstText)
            make?.height.mas_equalTo()(self.firstText)
        }
        equalLab.mas_updateConstraints { (make) in
            make?.right.mas_equalTo()(self.firstText.mas_left)?.offset()(-16)
            make?.centerY.mas_equalTo()(self.titleLab)?.offset()(40)
        }
        resultLab.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.firstText.mas_left)
            make?.centerY.mas_equalTo()(self.equalLab)
        }
        tipLab.mas_updateConstraints { (make) in
            make?.centerX.mas_equalTo()(self)
            make?.top.mas_equalTo()(self.resultLab.mas_bottom)?.offset()(16)
        }
    }
    
    lazy var titleLab:UILabel = {
        let lab = UILabel()
        lab.text = "贷款利率"
        return lab
    }()
    
    lazy var firstText:UITextField = {
        let textF = UITextField()
        textF.layer.borderWidth = 0.5
        textF.layer.borderColor = JYSeparatorLineColor.cgColor
        textF.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
        textF.leftViewMode = .always
        let lab = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 50))
        lab.text = "%"
        lab.textColor = JYDetailGrayColor
        lab.font = UIFont.systemFont(ofSize: 14)
        textF.rightView = lab
        textF.rightViewMode = .always
        textF.placeholder = "1.00"
        textF.keyboardType = .decimalPad
        textF.addTarget(self, action: #selector(caculateTheResultRate), for: .editingChanged)
        textF.delegate = self
        return textF
    }()
    
    lazy var typeLab:UILabel = {
        let lab = UILabel()
        lab.textAlignment = .center
        lab.text = "x"
        return lab
    }()
    lazy var secondText:UITextField = {
        let textF = UITextField()
        textF.layer.borderWidth = 0.5
        textF.layer.borderColor = JYSeparatorLineColor.cgColor
        textF.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
        textF.leftViewMode = .always
        let lab = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 50))
        lab.text = "倍"
        lab.textColor = JYDetailGrayColor
        lab.font = UIFont.systemFont(ofSize: 14)
        textF.rightView = lab
        textF.rightViewMode = .always
        textF.placeholder = "1.00"
        textF.keyboardType = .decimalPad
        textF.addTarget(self, action: #selector(caculateTheResultRate), for: .editingChanged)
        textF.delegate = self
        textF.text = "1.00"
        return textF
    }()
    lazy var equalLab:UILabel = {
        let lab = UILabel()
        lab.text = "="
        return lab
    }()
    lazy var resultLab:UILabel = {
        let lab = UILabel()
        
        return lab
    }()
    lazy var tipLab:UILabel = {
        let lab = UILabel()
        lab.textAlignment = .center
        lab.textColor = JYDetailGrayColor
        lab.font = UIFont.systemFont(ofSize: 12)
        lab.text = "当前基准利率:1%"
        return lab
    }()
}

//MARK : - 底部计算按钮
class JYHouseLoanCaculateBtnView: JYBaseView {
    lazy var caculateBtn:UIButton = {
        let btn = UIButton()
        btn.backgroundColor = JYDetailRedColor;
        btn.setTitle("开始计算", for: .normal)
        btn.layer.cornerRadius = 22;
        return btn
    }()
    override func setUpUI() {
        super.setUpUI()
        self.addSubview(caculateBtn)
    }
    override func setTheConstraints() {
        super.setTheConstraints()
        caculateBtn.mas_updateConstraints { (make) in
            make?.center.mas_equalTo()(self)
            make?.width.mas_equalTo()(self)?.multipliedBy()(0.8)
            make?.height.mas_equalTo()(44)
        }
    }
}

//MARK: - 自定义cell相关
enum JYHouseLoanCellMode : Int {
    
    case normal
    
    case one
    
    case two
    
}

class JYHouseLoanCell: JYBaseTableViewCell,UITextFieldDelegate {
    
    var model:JYHouseLoanModel = JYHouseLoanModel() {
        didSet{
            self.titleLab.text = model.title
            self.textField.text = model.descri
            self.textField.placeholder = model.defaultDescri
        }
    }
    
    var cellMode:JYHouseLoanCellMode = JYHouseLoanCellMode.normal {
        didSet{
                changeTheCellMode()
        }
    }
    
    //MARK: - UITextFieldDelegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string=="" {
            return true
        }
        if (textField.text! as NSString).length + (string as NSString).length > 11 {
            return false
        }
        if textField.text == "" && string == "." {
            return false
        }
        if (textField.text?.contains("."))! {
            if (textField.text!.components(separatedBy: ".").last! as NSString).length >= 2 || string.contains(".") {
                return false
            }
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.model.descri = textField.text!
    }
    
    override func setUpUI() {
        super.setUpUI()
        self.contentView.addSubview(titleLab)
        textField.leftViewMode = .always
        textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 5))
        textField.rightViewMode = .always
        textField.rightView = unit
        self.contentView.addSubview(textField)
        
        self.cellMode = .normal
    }
    
    ///修改cell模式时，则改变界面布局
    private func changeTheCellMode() {
        if cellMode == .normal {
            self.textField.rightViewMode = cellMode == .none ? .never : .always
            self.textField.rightView = cellMode == .none ? nil : self.unit
            self.textField.textColor = JYDetailGrayColor
        }else{
            self.textField.rightViewMode = cellMode == .none ? .never : .always
            self.textField.rightView = cellMode == .none ? nil : self.unit
            self.textField.textColor = UIColor.black
        }

        switch cellMode {
        case .one:
            self.titleLab.font = UIFont.systemFont(ofSize: 16)
            self.textField.layer.borderWidth = 0.5
            self.textField.font = UIFont.systemFont(ofSize: 16)
            self.textField.textAlignment = .left
            self.textField.isUserInteractionEnabled = true
            self.unit.isHidden = false
            self.unit.text = "万"
            break
        case .two:
            self.titleLab.font = UIFont.systemFont(ofSize: 14)
            self.textField.layer.borderWidth = 0.5
            self.textField.font = UIFont.systemFont(ofSize: 14)
            self.textField.textAlignment = .right
            self.textField.isUserInteractionEnabled = true
            self.unit.isHidden = false
            self.unit.text = "%"
            break
        default:
            self.titleLab.font = UIFont.systemFont(ofSize: 16)
            self.textField.layer.borderWidth = 0
            self.textField.font = UIFont.systemFont(ofSize: 12)
            self.textField.textAlignment = .right
            self.textField.isUserInteractionEnabled = false
            self.unit.isHidden = true
            break
        }
        setTheLayout()
    }
    
    override func setTheLayout() {
        super.setTheLayout()
        switch cellMode {
        case .one:
            self.titleLab.mas_updateConstraints { (make) in
                make?.left.mas_equalTo()(self.contentView)?.offset()(16)
                make?.centerY.mas_equalTo()(self.contentView)
            }
            self.textField.mas_updateConstraints { (make) in
                make?.left.mas_equalTo()(self.titleLab.mas_right)?.offset()(16)
                make?.centerY.mas_equalTo()(self.contentView)
                make?.right.mas_greaterThanOrEqualTo()(self.contentView)?.offset()(-16)
                make?.height.mas_equalTo()(35)
            }
            self.textField.setContentHuggingPriority(.fittingSizeLevel, for: .horizontal)
            break
        case .two:
            self.titleLab.mas_updateConstraints { (make) in
                make?.left.mas_equalTo()(self.contentView)?.offset()(32)
                make?.centerY.mas_equalTo()(self.contentView)
            }
            self.textField.mas_updateConstraints { (make) in
                make?.centerY.mas_equalTo()(self.contentView)
                make?.right.mas_greaterThanOrEqualTo()(self.contentView)?.offset()(-32)
                make?.height.mas_equalTo()(35)
                make?.width.mas_equalTo()(88)
            }
            self.textField.setContentHuggingPriority(.fittingSizeLevel, for: .horizontal)
            break
        default:
            self.titleLab.mas_updateConstraints { (make) in
                make?.left.mas_equalTo()(self.contentView)?.offset()(16)
                make?.centerY.mas_equalTo()(self.contentView)
            }
            self.textField.mas_updateConstraints { (make) in
                make?.centerY.mas_equalTo()(self.contentView)
                make?.right.mas_greaterThanOrEqualTo()(self.contentView)
                make?.height.mas_equalTo()(35)
            }
            self.textField.setContentHuggingPriority(.fittingSizeLevel, for: .horizontal)
            break
        }
    }
    
    /// 标题
    lazy var titleLab:UILabel = {
        let lab = UILabel()
        return lab
    }()
    
    /// 右侧UITextField
    lazy var textField:UITextField = {
        let textF = UITextField()
        textF.layer.borderColor = JYDetailGrayColor.cgColor
        textF.layer.borderWidth = 0.5
        textF.keyboardType = .decimalPad
        textF.delegate = self
        return textF
    }()
    
    /// UITextField中的单位
    lazy var unit: UILabel = {
        let lab = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 100))
        lab.textAlignment = .center
        lab.textColor = JYDetailGrayColor
        lab.text = "万"
        lab.font = UIFont.systemFont(ofSize: 16)
        return lab
    }()
}

